package com.eastcom.groovy.task.taskdirector.temp

import java.awt.TexturePaintContext.Int;
import java.sql.Timestamp
import java.sql.Types;
import java.text.SimpleDateFormat
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.eastcom.groovy.tools.common.JmsJndiConfig
import com.eastcom.groovy.tools.common.MQCommunication
import com.eastcom.groovy.tools.db.DbEngine
import com.eastcom.groovy.tools.file.FtpUtils;
import com.eastcom.groovy.provider.*

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPFile
import org.apache.commons.net.ftp.FTPFileFilter
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
 * 任务类，可配置
 * @author yuanyue
 *
 */
class SimpleTxtFileTaskDirector_Ftp_Alarmer_Empp {
	/************************配置属性，可以修改，请尽量使用英文防止中文编码问题***************************/
	final String[] ftpRemotePath = ["/home/dongxin/qixintong/log"]
	final String[] ftpLocalPath = ["/home/ipnet/mystope/data/empp"]
	final String ftpIp = "10.11.244.119"
	final String ftpUser = "dongxin"
	final String ftpPasswd = "dx@wlan"
	final int ftpPort = 21
	final int ftpFileLimit = 200
	final String ftpSystem = "UNIX"
	final String ftpControlEnCode = "UTF-8"
	final String ftpFileEnCode = "UTF-8"
	final String ftpServerLanguage = "zh"
	final String ftpFileNameRegex = "sh_wlan_empp\\.log\\.(\\d+)"
	final long fileLimit = 2000000
	final String dstdbBean = "oracle_39_nhm"
	final String timeFormat = "yyyy-MM-dd HH:mm:ss,sss"
	final String fileNameTimeFormat = "yyyyMMddHHmm"
	final String[] regex =
	[
		"([0-9]{4}-[0-9]{2}-[0-9]{2}\\s+[0-9]{1,}:[0-9]{1,}:[0-9]{1,},[0-9]{3})\\s+\\[Thread-(\\d+)\\]\\s+(\\w+)\\s+com.asiainfo.wlan.qxt.QxtSmsBusiness.*"
	]
	final int[][] groupId =
	[
		[1,2,3]
	]
	final int parseLineNumMinOnce = 1
	final int parseLineNumMaxOnce = 5
	final String objectId = "TEST"
	final String eventId = "TEST"
	final String insertSql = "insert into NHM_RADUIS_LOG_QXT_10MIN(START_TIME,FLOW_NO,CODETYPE,AGENTID) values(?,?,?,?)"
	/***************************可配置部分结束***********************************************/

















	static ThreadPoolTaskExecutor threadPoolTaskExecutor
	static MQCommunication mq
	static List<String> dstFieldList = new ArrayList()
	static int[] sqlTypes
	static List<Integer> dstFieldTypeList = new ArrayList()
	List<List<String>> parseResultList = new ArrayList()

	static Log logger = LogFactory.getLog(SimpleTxtFileTaskDirector_Ftp_Alarmer_Empp.class)


	/*********************initJob和doJob是要被程序调用的方法**************************/
	public boolean initJob(String jobId){
		doAlarmInit()
		doDbInit()
	}

	public boolean doJob(String jobId){
		doFtp()
		doParseFile()
		doAlarmerJob()
	}


	/************************下面是自己使用的方法**********************/
	private boolean doAlarmInit(){
		try{
			JmsJndiConfig jmsConfig = new JmsJndiConfig()
			jmsConfig.initialContextFactory = PropertyPlaceholderConfigurerProvider.getContextProperty("java.naming.factory.initial")
			jmsConfig.providerUrl = PropertyPlaceholderConfigurerProvider.getContextProperty("java.naming.provider.url")
			jmsConfig.securityAuthentication = PropertyPlaceholderConfigurerProvider.getContextProperty("java.naming.security.authentication")
			jmsConfig.securityPrincipal = PropertyPlaceholderConfigurerProvider.getContextProperty("java.naming.security.principal")
			jmsConfig.securityCredentials = PropertyPlaceholderConfigurerProvider.getContextProperty("java.naming.security.credentials")
			jmsConfig.referral = PropertyPlaceholderConfigurerProvider.getContextProperty("java.naming.referral")


			Map<String, Object> propertyMap = new HashMap()
			propertyMap.put("jmsJndiConfig", jmsConfig)
			propertyMap.put("factoryName", PropertyPlaceholderConfigurerProvider.getContextProperty("fm.sconnectionFactory"))
			println PropertyPlaceholderConfigurerProvider.getContextProperty("fm.sconnectionFactory")
			propertyMap.put("name", PropertyPlaceholderConfigurerProvider.getContextProperty("fm.squeueName"))
			DynamicBeanRegisterProvider beanRegister = SpringContextProvider.getBean("beanRegister")
			beanRegister.addBeanService("mqConnector","com.eastcom.groovy.tools.common.MQCommunication",propertyMap)
			println SpringContextProvider.getBean("mqConnector")
			mq = SpringContextProvider.getBean("mqConnector")
			mq.init()
		}catch (Exception e) {
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

	private doDbInit(){
		try{
			String reg = "\\w+\\s+\\w+([^\\(\\),]+)\\s*\\(([^\\)]+)"
			String dstTb
			String dstFields
			Pattern pattern = Pattern.compile(reg)
			Matcher matcher = pattern.matcher(insertSql)
			if(matcher.find()){
				dstTb = matcher.group(1)
				dstFields = matcher.group(2)
			}
			DbEngine.loadDb(dstdbBean, dstTb, dstFields, dstFieldList, dstFieldTypeList, true)
			sqlTypes = new int[dstFieldTypeList.size()]
			for(int i = 0; i < dstFieldTypeList.size(); i++){
				sqlTypes[i] = dstFieldTypeList.get(i)
			}
		}catch (Exception e) {
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

	private boolean doFtp(){
		try{
			FTPFile[] acceptFiles = null;
			FtpUtils ftpUtils = new FtpUtils();
			for(int i = 0; i < ftpRemotePath.length; i++){
				String rp = ftpRemotePath[i]
				String lp = ftpLocalPath[i]
				ftpUtils.login(ftpIp, ftpPort, ftpUser, ftpPasswd, ftpSystem, ftpControlEnCode, ftpServerLanguage);
				ftpUtils.getFtp().changeWorkingDirectory(rp);
				Pattern pat = Pattern.compile(ftpFileNameRegex);

				acceptFiles = ftpUtils.getFtp().listFiles(null, new FTPFileFilter() {
							private int fileCount = 0;
							@Override
							public boolean accept(FTPFile file) {
								// TODO 自动生成的方法存根
								String name = file.getName();
								Matcher mat = pat.matcher(name);
								boolean rs = mat.find();
								if(! rs){
									return false
								}
								String tm = mat.group(1)
								SimpleDateFormat simp = new SimpleDateFormat(fileNameTimeFormat)
								Date date = simp.parse(tm)
								Calendar fileLimitTime = Calendar.getInstance();
								fileLimitTime.setTimeInMillis(new Date().getTime() - 1000000);
								if(date.before(fileLimitTime.getTime())){
									return false
								}
								File localFile = new File(lp);
								String[] localFiles = localFile.list();
								if(localFiles != null){
									for(String lf: localFiles){
										if(lf.equalsIgnoreCase(name)){
											return false;
										}
									}
								}

								if(fileCount > ftpFileLimit){
									return false;
								}
								fileCount++;
								return true;
							}
						});
				boolean res = false;
				int count = 0;
				System.out.println("接收的文件数量："+acceptFiles.length);
				for(int j = 0; j < acceptFiles.length; j++){
					String fileName = acceptFiles[j].getName();
					File f = null;
					String dir = lp
					File dirFile = new File(dir);
					if(! dirFile.exists()){
						dirFile.mkdirs();
					}
					if(dir.endsWith("/")||dir.endsWith("\\")||dir.endsWith("\\\\")){

						f=new File(dir+fileName);
					}else{
						f=new File(dir+"/"+fileName);
					}
					OutputStream os=new FileOutputStream(f);
					res = ftpUtils.getFtp().retrieveFile(new String(fileName.getBytes(ftpFileEnCode),"ISO-8859-1"), os);
					if(res){
						count ++;
					}
					os.flush()
					os.close()
					//				logger.debug("下载了"+count+"文件！")
				}
			}
		}catch (Exception e) {
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

	private boolean doParseFile(){
		try{
			Calendar fileTime = Calendar.getInstance();
			Calendar fileLimitTime = Calendar.getInstance();
			fileLimitTime.setTimeInMillis(new Date().getTime() - fileLimit);
			for(int t = 0; t < ftpLocalPath.length; t++){
				File dirs = new File(ftpLocalPath[t])
				File[] dirFile = dirs.listFiles(new FilenameFilter() {

							@Override
							public boolean accept(File dir, String name) {
								// TODO 自动生成的方法存根
								if(name.matches(ftpFileNameRegex)){
									return true;
								}
								return false;
							}
						});
				for(File f: dirFile){
					long time = f.lastModified();
					fileTime.setTimeInMillis(time);
					if(fileTime.before(fileLimitTime)){
						continue;
					}
					String fileNameTime = null;


					BufferedReader reader = null;

					try {
						reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), ftpFileEnCode));
					} catch (Exception e) {
						e.printStackTrace()
					}
					for(int index = 0; index < regex.length; index++){
						String rg = regex[index]
						int[] gd = groupId[index]
						StringBuilder context = new StringBuilder();
						Pattern pat = Pattern.compile(rg);
						String line = null;
						boolean isFileEnd = false;
						int counts = 0
						boolean rs = false
						while(true){
							if(counts > parseLineNumMaxOnce){
								context = new StringBuilder();
							}
							if(parseResultList.size() >= 1500){
								doInsertResult()
							}
							for(int i = 0; i < parseLineNumMinOnce; i++){
								try {
									line = reader.readLine()
									if(line == null){
										isFileEnd = true
										break
									}
								} catch (Exception e) {
									e.printStackTrace()
								}
								context.append(line+"\n")
								counts++
							}
							if(context.toString().contains("手机号错误")){
								continue
							}
							Matcher mat = pat.matcher(context.toString());
							rs = mat.find();
							if(rs){
								context = new StringBuilder();
								List<String> valueList = new ArrayList<String>();
								for(int g : gd){
									String ct = mat.group(g)
									valueList.add(ct);
									println ct
								}
								parseResultList.add(valueList)
							}else{
							}
							if(isFileEnd){
								logger.debug("文件已经读完！");
								doInsertResult()
								break;
							}
						}
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

	private boolean doInsertResult(){
		try{
			DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
			dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(dstdbBean))
//			String sql2 = "select tt.agent_id AGENT_ID from rm.rm_device tt where tt.ip_addr='10.11.244.39'"
//			Map<String, Object> rs = dbEngine.getJdbcUtil().queryForMap(sql2)
			String agentId = "8a5dffbc2ffbb236012ffbb25b430000"
			println parseResultList.size()
			for(List<String> raw: parseResultList){
				Object[] param = new Object[raw.size()+1]
				param[raw.size()] = agentId
				for(int i = 0; i < raw.size(); i++){
					print raw.get(i)+"--"+sqlTypes[i]+"\t"
					try {
						switch(sqlTypes[i]){
							case Types.INTEGER:
								param[i] = Integer.valueOf(raw.get(i))
								break
							case Types.FLOAT:
							case Types.DOUBLE:
								param[i] = Double.valueOf(raw.get(i))
								break
							case Types.DECIMAL:
							case Types.NUMERIC:
								param[i] = BigDecimal.valueOf(Double.valueOf(raw.get(i)))
								break
							case Types.TIMESTAMP:
								java.util.Date date = new SimpleDateFormat(timeFormat).parse(raw.get(i))
								logger.debug(date)
								param[i] = new Timestamp(date.getTime())
								break
							case Types.DATE:
								java.util.Date date = new SimpleDateFormat(timeFormat).parse(raw.get(i))
								logger.debug(date)
								param[i] = new java.sql.Date(date.getTime())
								break
							case Types.VARCHAR:
							case Types.NVARCHAR:
								param[i] = raw.get(i)
								break
							case Types.OTHER:
								param[i] = raw.get(i)
								break;
							default:
								param[i] = null
								logger.warn("入库数据库字段无法识别！使用Null插入！")
								break;
						}
					} catch (Exception e) {
						e.printStackTrace()
						logger.error(e.getMessage())
						param[i]=null
					}
				}
				try {
					dbEngine.getJdbcUtil().update(insertSql, param, sqlTypes)
				} catch (Exception e) {
					e.printStackTrace()
				}
				println ""
			}
			println "sdfdsfdsdone!"
			parseResultList.clear()
		}catch (Exception e) {
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

	public boolean doAlarmerJob(){
		try{
			int count = 0
			List<Integer> flowNoList = new ArrayList()
			List<Map<String,Object>> alarmerList = new ArrayList()
			Timestamp time
			Timestamp maxTime
			String sql
			Calendar cl
			DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
			dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(dstdbBean))
			sql = "select max(START_TIME) TIMESTAMP from NHM_RADUIS_LOG_QXT_10MIN"
			List<Map<String,Object>> tempList = dbEngine.getJdbcUtil().queryForList(sql)
			time = tempList.get(0).get("TIMESTAMP")
			if(time == null){
				return true
			}
			boolean isEnd = false
			String agentId
			while(! isEnd){
				int[] sqlTypes = new int[2];
				Object[] params = new Object[2];
				sqlTypes[0] = Types.TIMESTAMP
				sqlTypes[1] = Types.TIMESTAMP

				cl = Calendar.getInstance()
				cl.setTimeInMillis(time.getTime())
				print cl
				cl.add(Calendar.DAY_OF_YEAR, -2)
				print cl
				println ""
				params[0] = new Timestamp(cl.getTime().getTime())
				params[1] = time
				maxTime = time
				time = params[0]
				println "查询参数:"+params[0]+"----"+params[1]
				sql = "select START_TIME,FLOW_NO,CODETYPE,AGENTID from NHM_RADUIS_LOG_QXT_10MIN where START_TIME >= ? and START_TIME <= ?"
				List<Map<String,Object>> resultList = dbEngine.getJdbcUtil().queryForList(sql, params, sqlTypes)
				if(resultList == null || resultList.isEmpty()){
					break
				}
				for(Map<String,Object> map : resultList){
					int flowNo = map.get("FLOW_NO")
					agentId = map.get("AGENTID")
					if(agentId == null){
						continue
					}
					if(! flowNoList.contains(flowNo)){
						flowNoList.add(flowNo)
						count++
					}
					alarmerList.add(map)
					if(count > 100){
						isEnd = true
						break
					}
				}
			}
			count = 0
			for(Map<String,Object> map : alarmerList){
				String codeType = map.get("CODETYPE")
				if(codeType.equals("FATAL") || codeType.equals("ERROR")){
					count++
				}
			}
			if(count > 10){
				java.util.Date date = new java.util.Date()
				date.setTime(maxTime.getTime())
				String msg ="{da||agent="+agentId+"||counts=1||messageid=IPNET_YAXIN_CONFIGFILE_QXT||message="
				msg += date.toString()+",企信通短信下发成功率为:"+(100-count)+"%||keyValue=notcare||kpiname=notcare}"
				println "发送的告警["+msg+"]"
				mq.sendMessage(msg)
			}
		}
		catch (Exception e) {
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}
}